package com.yun2.bms.controller.category;

import com.yun2.bms.dao.ICategoryDao;
import com.yun2.bms.dao.impl.CategoryDaoImpl;
import com.yun2.bms.model.Category;
import com.yun2.bms.service.ICategoryService;
import com.yun2.bms.service.impl.CategoryServiceImpl;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.ResourceBundle;

/**
 * author: youli
 * qq: 27855162@qq.com
 * date: 2020/5/25
 * 添加图书分类 控制器
 */

public class AddCategoryController implements Initializable {

    private ICategoryService categoryService = new CategoryServiceImpl();

    private ObservableList<Category> categoryData = FXCollections.observableArrayList();

    public ObservableList<Category> getCategoryData() {
        return categoryData;
    }

    public void setCategoryData(ObservableList<Category> categoryData) {
        this.categoryData = categoryData;
    }

    @FXML
    private Button btnCancel;

    @FXML
    private Button btnOK;

    @FXML
    private TextField tfCategoryName;

    @FXML
    void add(ActionEvent event) {
        String categoryName = this.tfCategoryName.getText();
        String info = "";
        if(StringUtils.isBlank(categoryName)){
            info = "分类名称不能为空！";
        }else if(categoryService.isCategoryNameUnique(categoryName)){
            info = "分类名称已经存在！";
        }else{
            Category category = new Category(categoryName);
            int id = categoryService.add(category);
            if(id > 0){
                category.setId(id);
                this.categoryData.add(category);
                info = "添加分类成功！";
            }else{
                info = "添加分类失败！";
            }
        }
        //关闭当前窗口
        closeWindow();
        //显示提示信息
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("提示信息");
        alert.setHeaderText(info);
        alert.showAndWait();
    }

    @FXML
    void cancel(ActionEvent event) {
        closeWindow();
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }

    private void closeWindow(){
        Stage stage = (Stage) this.btnOK.getScene().getWindow();
        stage.close();
    }
}
